<!--清扫保洁-->
<template>
  <div class="app-page">
    <div class="app-title">
      <h3>{{ config.smallTitle }}</h3>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['assetmanage:cleaning:range:export']"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['assetmanage:cleaning:range:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!multiple.list.length"
            @click="handleDelete"
            v-hasPermi="['assetmanage:cleaning:range:remove']"
            >删除</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="app-container">
      <div class="filter-box" v-show="showSearch">
        <AssetManageFilter
          :list="filter.list"
          :formData="filter.data"
          @handleQuery="handleQuery"
        >
          <template v-for="item in $options.dicts" v-slot:[item]>
            <el-option
              v-for="dict in dict.type[item]"
              :key="item + '_' + dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </template>
        </AssetManageFilter>
      </div>
      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['assetmanage:cleaning:range:export']"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['assetmanage:cleaning:range:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!multiple.list.length"
            @click="handleDelete"
            v-hasPermi="['assetmanage:cleaning:range:remove']"
            >删除</el-button
          >
        </el-col>

        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row> -->

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="55" align="center">
          <template #default="{ $index }">
            <div class="table-header flex h-center">
              <span>
                {{ page.size * (page.index - 1) + ($index + 1) }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in tableColumn"
          :key="item.field + '_' + index"
          :prop="item.field"
          :label="item.title"
          :show-overflow-tooltip="false"
          :min-width="item.width"
        >
          <template v-if="item.field == 'serviceType'">
            {{ config.title }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="page.total"
        :page.sync="page.index"
        :limit.sync="page.size"
        @pagination="getList"
      />
    </div>
    <DialogImport
      :dialog.sync="dialog"
      @importTemplate="importTemplate"
      @importSubmit="importSubmit"
    />
  </div>
</template>

<script>
import AssetManageFilter from "../../common/filter.vue";
import DialogImport from "../../common/dialog-import.vue";
import { FILTER } from "./filter.js";
import { COLUMN } from "./column.js";
import { MessageBox } from "element-ui";
import {
  assetTableList,
  assetTableDel,
  assetTableImport,
} from "@/api/assetmanage/cleaning";
import { listRegion } from "@/api/erecord/region";
export default {
  components: {
    AssetManageFilter,
    DialogImport,
  },
  name: "AssetManageClearningRange",
  dicts: ["assetmanage_cleaning_type"],
  data() {
    return {
      config: {
        // 类目
        title: "清扫保洁",
        // 维度
        smallTitle: "管理范围",
        // 模板下载链接
        templateUrl: "/asset/cleaning/importTemplate",
        // 查询列表方法
        requestList: assetTableList,
        // 删除方法
        requestDel: assetTableDel,
        // 导入方法
        requestImport: assetTableImport,
        // 导出链接
        requestIExport: "/asset/cleaning/exportCleaning",
      },
      // 显示搜索条件
      showSearch: true,
      filter: {
        data: {},
        list: [],
      },
      // 表格多选数据
      multiple: {
        list: [],
      },
      loading: true,
      tableData: [],
      tableColumn: JSON.parse(JSON.stringify(COLUMN)),
      page: {
        size: 10,
        index: 1,
        total: 0,
      },
      // 导入弹窗
      dialog: {
        title: "",
        visible: false,
      },
    };
  },
  created() {
    this.initFilter();
  },
  methods: {
    // 初始化筛选
    async initFilter() {
      const list = JSON.parse(JSON.stringify(FILTER));
      const data = {};
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.type == "inputArr") {
          item.field.forEach((el) => {
            data[el] = "";
          });
        } else if (item.type == "select" && item.multiple) {
          data[item.field] = [];
        } else {
          data[item.field] = "";
        }
        if (item.type == "select" && item.field == "communitySet") {
          item.list = await this.getRegion();
        }
      }
      this.filter.data = data;
      this.filter.list = list;
      this.page.index = 1;
      this.getList();
    },
    getRegion() {
      return new Promise((resolve) => {
        let params = {
          grade: 5,
        };
        listRegion(params).then((res) => {
          let list =
            res?.rows?.map((el) => {
              return {
                label: el.title,
                value: el.id,
              };
            }) ?? [];
          resolve(list);
        });
      });
    },
    // 导入
    handleImport() {
      this.dialog.title = `导入${this.config.title}${this.config.smallTitle}`;
      this.dialog.visible = true;
    },
    // 导入下载模板
    importTemplate() {
      if (!this.config.templateUrl) {
        return;
      }
      const url = this.config.templateUrl;
      const name = `导入${this.config.title}${this.config.smallTitle}模板.xlsx`;
      this.download(url, {}, name);
    },
    // 导入确认
    importSubmit(data, callback) {
      if (!this.config.requestImport) {
        callback && callback();
        return;
      }
      this.config
        .requestImport(data)
        .then((res) => {
          let isArr = Array.isArray(res.data);
          if (isArr && res.data.length) {
            let htmlText = `<h3 style="margin:0;margin-bottom:10px;">导入失败</h3>`;
            htmlText += `<div style="max-height:300px;overflow-y:auto">`;
            for (let i = 0; i < res.data.length; i++) {
              const el = res.data[i];
              htmlText += `<p style="color: #ff4949">${el}</p>`;
            }
            htmlText += `</div>`;
            MessageBox.alert(`${htmlText}`, "模板导入", {
              confirmButtonText: "重新上传",
              dangerouslyUseHTMLString: true,
            }).then(() => {
              this.handleImport();
            });
          } else {
            this.$modal.msgSuccess("导入成功");
            this.page.index = 1;
            this.getList();
          }
        })
        .finally(() => {
          callback && callback();
        });
    },
    // 导出
    handleExport() {
      if (!this.config.requestIExport) {
        return;
      }
      const url = this.config.requestIExport;
      const date = this.parseTime(new Date().getTime(), "{y}{m}{d}");
      const name = `${this.config.title}${this.config.smallTitle}列表${date}.xlsx`;
      this.download(
        url,
        {
          ...this.getParams(),
          pageNum: this.page.index,
          pageSize: this.page.size,
        },
        name
      );
    },
    // 删除
    handleDelete(row) {
      const ids = row.id || this.multiple.list;
      this.$modal
        .confirm("是否确认删除数据")
        .then(() => {
          this.loading = true;
          return this.config.requestDel(ids);
        })
        .then(() => {
          this.page.index = 1;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 搜索
    handleQuery() {
      this.page.index = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multiple.list = selection.map((item) => item.id);
    },
    getParams() {
      const filter = {};
      this.filter.list.forEach((item) => {
        if (item.type == "inputArr") {
          item.field.forEach((el) => {
            filter[el] = this.filter.data[el];
          });
        } else if (item.type == "select" && item.multiple) {
          filter[item.field] = this.filter.data[item.field].join(",");
        } else {
          filter[item.field] = this.filter.data[item.field];
        }
      });
      return filter;
    },
    getList() {
      if (!this.config.requestList) {
        this.loading = false;
        return;
      }
      const params = {
        ...this.getParams(),
        pageNum: this.page.index,
        pageSize: this.page.size,
      };
      this.loading = true;
      this.config.requestList(params).then((res) => {
        this.tableData = res.rows;
        this.page.total = res.total;
        this.loading = false;
      });
    },
  },
};
</script>
